package com.example.myblog.controller;

import com.example.myblog.dto.ChatRequest;
import com.example.myblog.dto.ChatResponse;
import com.example.myblog.service.AiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/assistant")
public class AssistantController {

    @Autowired
    private AiService aiService;

    @PostMapping("/chat")
    public ResponseEntity<ChatResponse> chat(@RequestBody ChatRequest request) {
        try {
            String message = request.getMessage();
            List<Map<String, String>> history = new ArrayList<>();
            if (request.getMessages() != null) {
                request.getMessages().forEach(m -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("role", m.getRole());
                    map.put("content", m.getContent());
                    history.add(map);
                });
            }
            if (message == null || message.isBlank()) {
                return ResponseEntity.badRequest().body(new ChatResponse(false, null, "消息内容不能为空"));
            }
            String reply = aiService.chat(message, history);
            return ResponseEntity.ok(new ChatResponse(true, reply, null));
        } catch (Exception e) {
            return ResponseEntity.ok(new ChatResponse(false, null, e.getMessage()));
        }
    }
}